package com.ypj.community.config;

import com.ypj.community.domain.LoginTicket;
import com.ypj.community.domain.User;
import com.ypj.community.service.UserService;
import com.ypj.community.util.CommunityConstant;
import com.ypj.community.util.CommunityUtil;
import com.ypj.community.util.CookieUtil;
import com.ypj.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers("/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like","/follow","/unfollow")
                .hasAnyAuthority(AUTHORITY_ADMIN,AUTHORITY_MODERATOR,AUTHORITY_USER)
                .antMatchers("/discuss/top",
                        "/discuss/wonderful")
                .hasAnyAuthority(AUTHORITY_MODERATOR)
                .antMatchers("/discuss/delete",
                        "/data/**")
                .hasAnyAuthority(AUTHORITY_ADMIN)
                .anyRequest().permitAll()
                .and().csrf().disable();
        //权限不够时
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //账号未登录时
                    @Override
                    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        String xRequestedWith=httpServletRequest.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)){//异步
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer=httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(4,"你还没有登录！"));
                        }else{
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //权限不足时
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith=httpServletRequest.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)){//异步
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer=httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(4,"无访问权限！"));
                        }else{
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/denied");
                        }
                    }
                });
        http.addFilterBefore(new Filter() {
            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                HttpServletRequest request = (HttpServletRequest) servletRequest;
                //获取cookie中凭证
                String ticket = CookieUtil.getValue(request, "ticket");
                if (ticket != null) {
                    //查询凭证
                    LoginTicket loginTicket = userService.findLoginTicket(ticket);
                    //判断凭证是否有效
                    if (ticket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                        //根据凭证查询用户
                        User user = userService.findUserById(loginTicket.getUserId());
                        //在本次请求中持有用户
                        hostHolder.setUsers(user);
                        //构建用户认证的结果，并存入SecurityContext,以便于Security进行授权
                        Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
                                userService.getAuthorities(user.getId()));
                        SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
                    }
                }
                filterChain.doFilter(request, response);
            }
        }, UsernamePasswordAuthenticationFilter.class);

        //Security底层默认会拦截/logout请求，进行退出处理。
        //覆盖默认逻辑才能执行我们自己的代码
        http.logout().logoutUrl("/securityLogout");
    }
}
